import ky, { type Options as KyOptions } from "ky";
import { LOCAL_STORAGE_KEY_TOKEN } from "../misc/dicts";

export type GraphQLResultOK = {
  data: Record<string, unknown>;
};

export type GraphQLResultFailed = {
  data: Record<string, unknown> | null;
  errors: {
    message: string;
    extensions?: Record<string, unknown>;
  }[];
};

export type GraphQLResult = GraphQLResultOK | GraphQLResultFailed;

async function request(options: { json: unknown; muted?: boolean }): Promise<GraphQLResult> {
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    Accept: "application/json",
  };

  const token = localStorage.getItem(LOCAL_STORAGE_KEY_TOKEN);
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  const kyOptions: KyOptions = { method: "post", json: options.json, headers };

  if (options.muted) {
    // @ts-expect-error TODO: 处理弹窗
    conf.muted = true;
  }

  const resp = ky("/graphql", kyOptions);

  // TODO: 更细致的处理
  return await resp.json();
}

export async function graphql(query: string, variables?: Record<string, unknown>) {
  const result = await request({ json: { query, variables: variables || {} } });
  if ("errors" in result) {
    throw new Error(result.errors[0].message);
  }
  return result.data;
}
